package com.bstek.uflo.form.controller;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.util.SerializationUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import com.bstek.dorado.web.resolver.AbstractResolver;
import com.bstek.uflo.command.CommandService;
import com.bstek.uflo.form.command.GetFormCommand;
import com.bstek.uflo.form.model.Form;

/**
 * @author Jacky.gao
 * @since 2013年11月13日
 */
public class LoadFormController extends AbstractResolver {
	private CommandService commandService;
	@Override
	protected ModelAndView doHandleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String formId=request.getParameter("formId");
		Map<String,Object> map=null;
		if(StringUtils.hasText(formId)){
			Form form=commandService.executeCommand(new GetFormCommand(Long.valueOf(formId)));
			String content=(String)SerializationUtils.deserialize(form.getContent());
			map=new HashMap<String,Object>();
			map.put("content", content);
			map.put("name", form.getName());
			map.put("id", form.getId());
		}
		ObjectMapper mapper=new ObjectMapper();
		response.setContentType("text/json");  
		response.setCharacterEncoding("UTF-8");  
		OutputStream out=response.getOutputStream();
		try{
			if(map==null){
				mapper.writeValue(out, "");				
			}else{
				mapper.writeValue(out, map);								
			}
		}finally{
			out.flush();
			out.close();
		}
		return null;
	}
	public CommandService getCommandService() {
		return commandService;
	}
	public void setCommandService(CommandService commandService) {
		this.commandService = commandService;
	}
}
